<template>
	<view class="content integrated-page page-wrapper-with-custom-tabbar">
		<!-- 背景层 -->
		<view class="page-background" v-if="currentTab === 2"></view>

		<!-- 1. 固定的 Tab 切换栏 -->
		<view class="fixed-header" :class="{'fixed-header-none': currentTab === 2, 'fixed-header-sticky': isSticky}"
			id="fixed-header" :style="topBarStyle">
			<u-tabs :list="tabList" :current="currentTab" @change="changeTab" :scrollable="false"
				:activeStyle="{ color: '#000000',fontWeight:'bolder',fontSize:'36rpx' }"
				:inactiveStyle="{ color: '#000000',fontSize:'32rpx'}" :itemStyle="{ height: '100rpx' }"
				:lineColor="`url(${lineBg}) 100% 100%`" lineHeight="16" lineWidth="40">
				<!--  #ifndef MP-WEIXIN || H5 || APP -->
				<view slot="left" style="padding-left: 20rpx;" @tap="$u.toast('列表被点击')">
					<u-icon name="list" size="28" color="#000000" bold></u-icon>
				</view>
				<view slot="right" style="padding-right: 20rpx;" @tap="$u.toast('搜索框被点击')">
					<u-icon name="search" size="30" color="#000000"></u-icon>
				</view>
				<!--  #endif  -->
			</u-tabs>

			<u-tabs id="fixed-header-time-axis" v-show="currentTab == 1" class="sub-category-tabs"
				:list="subCategoryTags" :current="currentSubCategoryTag" @change="handleSubCategoryTabChange"
				lineColor="none" lineWidth="100rpx" :activeStyle="{ color: '#FE772E', fontWeight: 'bold' }"
				:inactiveStyle="{ color: '#000' }" :itemStyle="{ height: '70rpx' }">
				<view slot="right" style="padding-left: 4px;padding-top: 4rpx;">
					<u-icon name="arrow-down" size="14" bold color="#000"></u-icon>
				</view>
			</u-tabs>
			<view class="header-sticky-sgz" v-show="currentTab === 2 && isSelf">
				<view class="header-sticky-sgz-item" @click="showAll = true">
					选择同行人
				</view>
				<view class="header-sticky-sgz-item" @click="showDate=true">
					生成相册
				</view>
				<view class="header-sticky-sgz-item" @click="showRightPopup = true">
					时光目录
				</view>
			</view>

		</view>

		<!-- 2. 为每个tab使用独立的scroll-view -->
		<!-- 关注 Tab -->
		<scroll-view v-show="currentTab === 0" class="main-scroll-view" :style="getScrollViewStyle(0)" scroll-y
			:refresher-enabled="true" :refresher-triggered="followData.refreshing"
			@refresherrefresh="() => handleRefresh(0)" @scrolltolower="() => handleScrollToLower(0)"
			@scroll="(e) => handleScroll(e, 0)" :show-scrollbar="false">

			<!-- 内容区域 -->
			<view class="content-area">
				<view class="post-list-container">
					<commonPost ref="followPostRef" :list="followData.list" @detailClick="handleDetailClickAll" />
				</view>
			</view>
		</scroll-view>

		<!-- 发现 Tab -->
		<scroll-view v-show="currentTab === 1" class="main-scroll-view" :style="getScrollViewStyle(1)" scroll-y
			:refresher-enabled="true" :refresher-triggered="discoveryData.refreshing"
			@refresherrefresh="() => handleRefresh(1)" @scrolltolower="() => handleScrollToLower(1)"
			@scroll="(e) => handleScroll(e, 1)" :show-scrollbar="false">

			<!-- 内容区域 -->
			<view class="content-area">
				<view class="post-list-container">
					<commonPost ref="discoveryPostRef" :list="discoveryData.list" @detailClick="handleDetailClickAll" />
				</view>
			</view>
		</scroll-view>

		<!-- 时光轴 Tab -->
		<scroll-view v-show="currentTab === 2" class="main-scroll-view" :style="getScrollViewStyle(2)" scroll-y
			:refresher-enabled="true" :refresher-triggered="timelineData.refreshing"
			@refresherrefresh="() => handleRefresh(2)" @scrolltolower="() => handleScrollToLower(2)"
			@scroll="(e) => handleScroll(e, 2)" :show-scrollbar="false" :scroll-into-view="scrollIntoView"
			:scroll-with-animation="true">

			<!-- 时光轴特有的头部信息 -->
			<view class="header" v-if="isSelf">
				<view class="header-data">
					<view class="header-data-dzxc">
						<view>我的数据</view>
					</view>
					<view class="data-container">
						<view class="data-item">
							<text class="data-value">{{statsData.tripCount||0}}</text>
							<text class="data-label">旅行次数（次）</text>
						</view>
						<view class="data-item">
							<text class="data-value">{{statsData.destinationCount||0}}</text>
							<text class="data-label">旅行地点（个）</text>
						</view>
						<view class="data-item">
							<text class="data-value">{{statsData.fellowsCount||0}}</text>
							<text class="data-label">同行人数（人）</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 内容区域 -->
			<view class="content-area">
				<view class="timeline-container">
					<u-empty mode="data" text="暂无动态，快去发布第一条吧"
						v-if="timelineData.list.length === 0 && !timelineData.isLoading" marginTop="100"></u-empty>
					<time-line v-else ref="timeline" location="left" :timeLineList="timelineData.list"
						:isLoad="timelineData.isLoading && timelineData.list.length === 0"
						@detailClick="handleDetailClick" @refreshData="() => handleRefresh(2)">
					</time-line>
					<u-loadmore v-if="!timelineData.list.length === 0" :status="timelineData.loadStatus" />
				</view>
			</view>
		</scroll-view>

		<Tabbar :tabbar-index="3" />
		<PublishPopup :show="showPublishPopup" @close="showPublishPopup = false" />

		<!-- 弹窗组件 -->
		<u-calendar :show="showDate" mode="range" title="请选择日期范围" color="#FFAE1A" @confirm="confirm"
			@close="showDate=false"></u-calendar>

		<!-- 生成电子相册-选择日期后打开，需要用户输入相册名称 -->
		<u-popup :show="showEmitAddAlbum" :round="10" mode="center" @close="SelectAddressPopup = false"
			:closeOnClickOverlay="false">
			<view class="SelectAddressPopupStyle">
				<view class="header-title">
					<u--input placeholder="请填写相册名称" border="surround" v-model="typeName"></u--input>
				</view>
				<view class="footer-btn">
					<view class="footer-btn-item cancel" @click="showEmitAddAlbum = false">
						取消
					</view>
					<view class="footer-btn-item confirm" @click="switchAddress()">
						创建
					</view>
				</view>
			</view>
		</u-popup>

		<u-popup :show="showRightPopup" mode="right" @close="showRightPopup = false" bgColor="transparent">
			<view class="rightPopup-line">
				<!-- 新增状态栏占位 -->
				<view class="status-bar-placeholder"></view>

				<view class="rightContent">
					<view class="rightContent-year" v-for="(years,index) in yearList" :key="index">
						<view class="rightContent-year-top">
							<view class="rightContent-year-val">
								{{ years.year }}
							</view>
							<view class="rightContent-year-picture">
								<image src="/static/time-axis/right-line-circle.png" mode=""></image>
							</view>
						</view>
						<view class="rightContent-year-bottom">
							<view class="rightContent-year-bottom-month" v-for="(months,mts) in years.monthList"
								:key="mts" @click="scrollToMonth(years.year, months.month)">
								{{ months.month }} 月
							</view>
						</view>
					</view>
				</view>
				<view class="rightImg">
					<image src="/static/time-axis/line-right.png" mode=""></image>
				</view>
			</view>
		</u-popup>
		<QianziyuSelect :show="showAll" type="checkbox" :showSearch="false" popupTitle="选择同行人" :dataLists="friendList"
			@cancel="onCancel" @submit="onFriends"></QianziyuSelect>
		<richPostDetail :show="showRichPostDetail" @close="showRichPostDetail = false" :postData="currentDetail" />
	</view>
</template>

<script>
	import NavBar from "@/components/common-nav/common-nav.vue"
	import commonTab from '@/components/common-tab/common-tab.vue';
	import commonPost from '@/components/common-post/common-post.vue';
	import Tabbar from "@/components/tabbar/tabbar.vue";
	import PublishPopup from '@/components/PublishPopup/PublishPopup.vue';
	import timeLine from "@/components/time-line/time-line.vue";
	import QianziyuSelect from "@/components/qianziyu-select/qianziyu-select.vue";
	import richPostDetail from '@/components/richPostDetail/richPostDetail.vue';
	import {
		getOwnPosts,
		getFriendsList,
		getOwnPostsInfoCount,
		getPosts,
		addClientImages,
	} from '@/request/api.js';

	const PAGE_SIZE = 10;
	const TAB_BAR_HEIGHT = 50; // px

	export default {
		components: {
			NavBar,
			commonTab,
			commonPost,
			Tabbar,
			PublishPopup,
			timeLine,
			QianziyuSelect,
			richPostDetail
		},
		data() {
			return {
				showPublishPopup: false, // 控制弹窗的显示与隐藏
				showEmitAddAlbum: false, //电子相册确认弹框
				typeName: '', //电子相册弹框内输入的相册名称
				currentTab: 1, // 默认显示发现
				tabList: [{
					name: '关注'
				}, {
					name: '发现'
				}, {
					name: '时光轴'
				}],
				subCategoryTags: [{
						name: '全部'
					}, {
						name: '热门'
					}, {
						name: '同城'
					}, {
						name: '美食'
					},
					{
						name: '购物'
					}, {
						name: '晒照'
					}, {
						name: '穿搭'
					}, {
						name: '指南'
					}
				],
				currentSubCategoryTag: 0,
				lineBg: require('@/static/index_line.png'),

				// 动态计算的高度和偏移
				fixedHeaderHeight: 0, // 整个顶部导航（一级和二级）高度
				tabbarHeight: 0,
				fixedHeaderTimeAxisHeight: 0, // 二级导航高度

				// 数据状态 - 为每个tab添加独立的刷新状态
				followData: this.createInitialListData(),
				discoveryData: this.createInitialListData(),
				timelineData: this.createInitialListData(),

				// 时光轴特有状态
				isSelf: true,
				statsData: {},
				showDate: false,
				showAll: false,
				selectFriends: null,
				friendList: [],
				cachedSelectFriendIcon: '/static/release/icon_xztxr.png',

				// 时光目录
				showRightPopup: false,
				yearList: [],
				scrollIntoView: '',

				// 新增：为每个tab维护独立的滚动位置和scroll-view引用
				tabScrollPositions: [0, 0, 0],
				scrollViewRefs: [null, null, null],
				isSticky: false,

				// 详情弹框（时光轴）前一个写的乱的很，堆屎，一个页面三个tabs前两个封装的好好的，第三个时光轴··一言难尽
				showRichPostDetail: false,
				currentDetail: {},
			};
		},
		onReady() {
			// 在 onReady 中获取，确保 DOM 已经渲染
			this.getHeaderHeight();
			// 获取 scroll-view 引用
			this.$nextTick(() => {
				this.initScrollViewRefs();
			});
		},
		onLoad() {
			// 监听全局弹窗事件
			uni.$on('togglePublishPopup', this.handleTogglePublishPopup);
			const systemInfo = uni.getSystemInfoSync();
			this.tabbarHeight = systemInfo.safeAreaInsets.bottom > 0 ? TAB_BAR_HEIGHT : (systemInfo.screenHeight -
				systemInfo.safeArea.bottom) + TAB_BAR_HEIGHT;

			this.initAllTabsData();
		},
		onUnload() {
			// 移除事件监听，防止内存泄漏
			uni.$off('togglePublishPopup', this.handleTogglePublishPopup);
		},
		onHide() {
			// 当页面被隐藏时（例如切换Tab），强制关闭弹窗
			this.showPublishPopup = false;
		},
		computed: {
			topBarStyle() {
				// #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-QQ
				if (this.$store.state.systemInfo.capsuleInfo.width > 0) {
					const paddingRight = this.$store.state.systemInfo.capsuleInfo.width + this.$store.state.systemInfo
						.capsuleRightPadding * 2;
					const paddingTop = this.$store.state.systemInfo.statusBarHeight + this.$store.state.systemInfo
						.capsuleRightPadding

					return `padding-right: ${paddingRight}px;padding-top:${paddingTop}px`;
				}
				// #endif

				// #ifdef APP-PLUS || H5
				return `padding-top: ${uni.getSystemInfoSync().statusBarHeight}px;`;
				// #endif

				// 在非小程序平台或计算完成前，返回一个空字符串
				return '';
			}
		},
		watch: {
			currentTab: {
				handler(val) {
					// 切换tab时重置吸顶状态
					this.isSticky = false;
				},
				immediate: true
			}
		},
		onBackPress(options) {
			// 优先关闭发布弹窗
			if (options.from === 'backbutton' && this.showPublishPopup) {
				this.showPublishPopup = false;
				return true;
			}
			
			// 优先关闭详情弹框
			if (options.from === 'backbutton' && this.showRichPostDetail) {
				// 需要触发组件的关闭
				this.showRichPostDetail = false
				return true;
			}
			return true;
		},
		
		methods: {
			// 初始化scroll-view引用
			initScrollViewRefs() {
				const query = uni.createSelectorQuery().in(this);
				for (let i = 0; i < 3; i++) {
					query.select(`.main-scroll-view:nth-child(${i + 3})`).node(res => {
						if (res && res.node) {
							this.scrollViewRefs[i] = res.node;
						}
					});
				}
				query.exec();
			},

			// 获取scroll-view样式
			getScrollViewStyle(tabIndex) {
				if (tabIndex == 0) {
					// 关注页面
					return `margin-top: ${this.fixedHeaderTimeAxisHeight}px;height:calc(100% - ${this.fixedHeaderTimeAxisHeight}px);border-top: 1rpx solid #F4F4F4;`
				} else if (tabIndex == 1) {
					// 发现页面
					return `margin-top: ${this.fixedHeaderHeight}px;height:100%;`
				} else if (tabIndex == 2) {
					// 时光轴页面
					return `margin-top: ${this.fixedHeaderHeight}px;height:calc(100vh - ${this.fixedHeaderHeight}px - ${this.tabbarHeight}px);`
				}
				return '';
			},

			// 处理滚动事件
			handleScroll(e, tabIndex) {
				const scrollTop = e.detail.scrollTop;
				// 实时更新当前tab的滚动位置
				this.tabScrollPositions[tabIndex] = scrollTop;

				// 在时光轴页面，当滚动超过一定距离时添加吸顶样式
				if (tabIndex === 2) {
					this.isSticky = scrollTop > 50;
				}
			},

			// 切换Tab
			changeTab(item) {
				if (this.currentTab === item.index) {
					// 点击当前Tab，回到顶部
					this.scrollToTop(this.currentTab);
					return;
				}

				this.currentTab = item.index;

				const currentData = [this.followData, this.discoveryData, this.timelineData][this.currentTab];
				// 如果切换到的Tab是空的，则加载数据
				if (currentData.list.length === 0 && currentData.hasMore) {
					this.fetchDataForTab(this.currentTab, true);
				}
			},

			// 滚动到顶部
			scrollToTop(tabIndex) {
				this.tabScrollPositions[tabIndex] = 0;
				this.isSticky = false;
				// 使用对应tab的scroll-view滚动方法
				if (this.scrollViewRefs[tabIndex]) {
					this.scrollViewRefs[tabIndex].scrollTo({
						top: 0,
						animated: true
					});
				}
			},

			// 下拉刷新
			handleRefresh(tabIndex) {
				const dataMap = [this.followData, this.discoveryData, this.timelineData];
				dataMap[tabIndex].refreshing = true;
				this.fetchDataForTab(tabIndex, true);
			},

			// 上拉加载更多
			handleScrollToLower(tabIndex) {
				if (tabIndex == 2) return
				this.fetchDataForTab(tabIndex, false);
			},

			// 修改 scrollToMonth 方法
			scrollToMonth(year, month) {
				// 构造目标年月的时间范围
				const targetDate = new Date(year, month - 1, 1);
				const targetYear = targetDate.getFullYear();
				const targetMonth = targetDate.getMonth();

				// 查找第一条匹配该年月的数据
				const index = this.timelineData.list.findIndex(item => {
					const itemDate = new Date(item.createTime || item.travelDate);
					return itemDate.getFullYear() === targetYear && itemDate.getMonth() === targetMonth;
				});

				if (index !== -1) {
					// 关闭弹窗
					this.showRightPopup = false;

					// 延迟一小段时间确保弹窗关闭后再滚动
					setTimeout(() => {
						// 使用 scroll-into-view 滚动到指定元素
						this.scrollIntoView = `timeline${index}`;

						// 重置 scrollIntoView，以便下次可以再次滚动到同一元素
						this.$nextTick(() => {
							setTimeout(() => {
								this.scrollIntoView = '';
							}, 100);
						});
					}, 300);
				} else {
					uni.showToast({
						title: '未找到该月份的数据',
						icon: 'none'
					});
				}
			},

			// 获取固定头部的高度，用于设置占位垫片
			getHeaderHeight() {
				const query = uni.createSelectorQuery().in(this);
				query.select('#fixed-header').boundingClientRect(data => {
					if (data) {
						this.fixedHeaderHeight = data.height;
					}
				}).exec();
				query.select('#fixed-header-time-axis').boundingClientRect(data => {
					if (data) {
						this.fixedHeaderTimeAxisHeight = this.fixedHeaderHeight - data.height;
					}
				}).exec();
			},

			// 创建初始数据结构
			createInitialListData() {
				return {
					list: [],
					pageNum: 1,
					loadStatus: 'loadmore',
					hasMore: true,
					isLoading: false,
					refreshing: false
				};
			},

			// 初始化所有Tab的数据
			initAllTabsData() {
				Promise.all([
					this.fetchDataForTab(0, true),
					this.fetchDataForTab(1, true),
					this.fetchDataForTab(2, true)
				]).catch(err => {
					console.error("初始化所有Tab数据时出错:", err);
				});
				this.getFriendsList();
				this.getOwnPostsInfo();
			},

			// 统一的数据获取函数
			async fetchDataForTab(tabIndex, isRefresh = false) {
				const dataMap = [this.followData, this.discoveryData, this.timelineData];
				const tabData = dataMap[tabIndex];

				if (tabData.isLoading || (!tabData.hasMore && !isRefresh)) {
					if (isRefresh) tabData.refreshing = false;
					return;
				}

				if (isRefresh) {
					tabData.pageNum = 1;
					tabData.list = [];
					tabData.hasMore = true;
					// 刷新时重置该tab的滚动位置
					this.tabScrollPositions[tabIndex] = 0;
				}

				tabData.isLoading = true;
				tabData.loadStatus = tabData.pageNum > 1 ? 'loading' : 'loadmore';

				const {
					api,
					params
				} = this.getApiAndParamsForTab(tabIndex);
				if (!api) {
					tabData.isLoading = false;
					tabData.refreshing = false;
					return;
				}

				try {
					const res = await api({
						...params,
						pageNum: tabData.pageNum,
						pageSize: PAGE_SIZE
					});
					const rows = res.data.rows || [];

					const formattedList = rows.map(item => this.formatItem(item, tabIndex));
					tabData.list.push(...formattedList);
					if (tabIndex == 2) {
						this.formatsRightPopup(tabData)
					}
					tabData.hasMore = rows.length === PAGE_SIZE;
					tabData.loadStatus = tabData.hasMore ? 'loadmore' : 'nomore';
					if (tabData.hasMore) {
						tabData.pageNum++;
					}
				} catch (error) {
					console.error(`加载Tab ${tabIndex} 数据失败:`, error);
					tabData.loadStatus = 'loadmore';
				} finally {
					tabData.isLoading = false;
					tabData.refreshing = false;
				}
			},

			// 根据Tab索引获取API和参数
			getApiAndParamsForTab(tabIndex) {
				const userId = this.$store.state.userInfo.userId;
				switch (tabIndex) {
					case 0:
						return {
							api: getPosts,
								params: {
									userId,
									queryType: 22
								}
						};
					case 1:
						return {
							api: getPosts, params: {
								userId,
								queryType: 21
							}
						};
					case 2:
						const fellowsIds = this.selectFriends ? this.selectFriends.map(f => f.id) : [];
						return {
							api: getOwnPosts, params: {
								userId,
								fellowsIds
							}
						};
					default:
						return {};
				}
			},

			// 格式化不同Tab的数据项
			formatItem(item, tabIndex) {
				if (tabIndex === 2) {
					return {
						...item,
						title: this.formatDateTime(item.travelDate) || item.createTime,
						cityName: item.location || "未确定具体地点",
						province: item.province || "未确定省份",
						imageList: item.files || []
					};
				}
				return item;
			},
			// 格式化时光轴右侧的时光目录
			formatsRightPopup(tableData) {
				// 用于存储按年份分组的数据
				const yearMap = new Map();

				// 遍历所有数据项，按年份和月份分组
				tableData.list.forEach(item => {
					const createTime = item.createTime || item.travelDate;
					if (createTime) {
						const date = new Date(createTime);
						const year = date.getFullYear();
						const month = date.getMonth() + 1; // 月份从0开始，需要+1

						// 如果该年份还未存在，初始化
						if (!yearMap.has(year)) {
							yearMap.set(year, {
								year: year,
								monthList: []
							});
						}

						// 获取该年份的数据
						const yearData = yearMap.get(year);

						// 检查该月份是否已存在，避免重复
						const monthExists = yearData.monthList.some(m => m.month === month);
						if (!monthExists) {
							yearData.monthList.push({
								month: month
							});
						}
					}
				});

				// 将Map转换为数组，并按年份降序排列
				this.yearList = Array.from(yearMap.values()).sort((a, b) => b.year - a.year);

				// 对每个月份列表按月份降序排列
				this.yearList.forEach(yearItem => {
					yearItem.monthList.sort((a, b) => b.month - a.month);
				});
			},

			// ------ 时光轴特有的方法 ------
			getFriendsList() {
				getFriendsList().then(res => {
					let list = [];
					if (res.data && res.data.data && res.data.data.groupedArray) {
						res.data.data.groupedArray.forEach(group => {
							list.push(...group.map(i => ({
								name: i.nickName,
								id: i.userId,
								avatar: i.avatar
							})));
						});
					}
					this.friendList = list;
				});
			},
			getOwnPostsInfo() {
				getOwnPostsInfoCount().then(res => {
					this.statsData = res.data.data;
				});
			},
			onCancel() {
				this.showAll = false;
				if (this.selectFriends) {
					this.selectFriends = null;
					this.fetchDataForTab(2, true);
				}
			},
			onFriends(e) {
				this.selectFriends = e;
				this.showAll = false;
				this.fetchDataForTab(2, true);
			},
			onSelectFriend() {
				return this.selectFriends ? this.selectFriends.map(p => p.name).join('、') : false;
			},
			confirm(e) {
				this.showDate = false;
				// addClientImages
				this.showEmitAddAlbum = true
			},
			formatDateTime(time) {
				if (!time) return null;
				const date = new Date(time);
				return `${date.getFullYear()}-${("0" + (date.getMonth() + 1)).slice(-2)}-${("0" + date.getDate()).slice(-2)}`;
			},
			/**
			 * @description 统一处理所有子组件的帖子点击事件
			 * @param {object} payload - 包含 { item, scroll } 的事件对象
			 */
			handleDetailClick(payload) {
				this.currentDetail = payload.item
				this.showRichPostDetail = true
			},
			handleDetailClickAll(payload) {
				this.currentDetail = payload
				this.showRichPostDetail = true
			},
			/**
			 * @description 处理从详情页返回的数据，并更新对应列表中的帖子状态
			 * @param {object} data - 详情页通过 eventChannel.emit('returnData', ...) 返回的数据
			 */
			handleDataFromDetail(data) {
				if (!data || !data.id) return;

				const findAndUpdatePost = (list) => {
					const index = list.findIndex(p => p.id === data.id);
					if (index > -1) {
						const postToUpdate = list[index];

						switch (data.type) {
							case 0: // 点赞状态更新
								if (data.isLiked !== undefined) {
									this.$set(postToUpdate, 'isLiked', data.isLiked);
								}
								if (data.likeCount !== undefined) {
									this.$set(postToUpdate, 'likeCount', data.likeCount);
								}
								break;
							case 1: // 评论数更新
								this.$set(postToUpdate, 'commentCount', (postToUpdate.commentCount || 0) + 1);
								break;
							case 2: // 收藏状态更新
								if (data.isCollected !== undefined) {
									this.$set(postToUpdate, 'isCollected', data.isCollected);
								}
								if (data.collectCount !== undefined) {
									this.$set(postToUpdate, 'collectCount', data.collectCount);
								}
								break;
							case 4: // 关注状态更新
								if (data.userId !== undefined && data.isFollowed !== undefined) {
									this.updateFollowStatusForAllPosts(data.userId, data.isFollowed);
								}
								break;
						}
						return true;
					}
					return false;
				};

				findAndUpdatePost(this.followData.list);
				findAndUpdatePost(this.discoveryData.list);
				findAndUpdatePost(this.timelineData.list);
			},

			/**
			 * @description 当一个作者的关注状态改变时，更新所有列表中该作者帖子的关注状态
			 * @param {string|number} userId - 作者ID
			 * @param {boolean} newFollowStatus - 新的关注状态 (true/false)
			 */
			updateFollowStatusForAllPosts(userId, newFollowStatus) {
				const statusValue = newFollowStatus ? 1 : 0;

				const updateList = (list) => {
					list.forEach(post => {
						if (post.userId === userId) {
							this.$set(post, 'isFollowed', statusValue);
						}
					});
				};

				updateList(this.followData.list);
				updateList(this.discoveryData.list);
				updateList(this.timelineData.list);
			},
			handleTogglePublishPopup() {
				const pages = getCurrentPages();
				const currentPage = pages[pages.length - 1];
				if (currentPage.route === 'pages/time-axis/time-axis') {
					this.showPublishPopup = !this.showPublishPopup;
				}
			},
			handleSubCategoryTabChange(e) {
				this.currentSubCategoryTag = e.index;
			},
		}
	}
</script>

<style lang="scss" scoped>
	::v-deep .u-tabs__wrapper__nav__line {
		z-index: -1;
		bottom: 15rpx;
	}

	page {
		overflow: hidden;
		background-color: #F8FAFB;
	}

	/* --- 新增的关键代码 --- */
	.page-wrapper-with-custom-tabbar {
		padding-bottom: calc(102rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(102rpx + env(safe-area-inset-bottom));
	}

	.main-scroll-view {
		height: 100%;
		margin-top: 100rpx;
	}

	/* 时光轴背景层 */
	.page-background {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-image: url('/static/time-axis-bg.png');
		background-size: cover;
		background-position: center;
		z-index: -1;
	}

	/* --- 新增结束 --- */
	.integrated-page {
		padding: 0 !important;
		height: 100vh;
		display: flex;
		flex-direction: column;
	}

	.fixed-header {
		position: fixed;
		width: 100%;
		top: 0;
		left: 0;
		z-index: 999;
		background-color: #ffffff;
		transition: all 0.3s ease;

		// 时光轴页面默认透明背景
		&.fixed-header-none {
			background-color: transparent;
		}

		// 吸顶时的样式
		&.fixed-header-sticky {
			background-color: #ffffff !important;
			box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);

			// 时光轴页面的吸顶header
			&.fixed-header-none {
				background-color: rgba(255, 255, 255, 0.95) !important;
				backdrop-filter: blur(10rpx);
			}
		}

		.sub-category-tabs {
			margin: 0 20rpx;
			padding-right: 10rpx;
			border-bottom: 1rpx solid #F4F4F4;
			border-top: 1rpx solid #F4F4F4;
		}
	}

	.header-placeholder {
		flex-shrink: 0;
	}

	.header-sticky-sgz {
		display: flex;
		justify-content: space-between;
		margin: 0 30rpx;
		padding: 20rpx 0;

		.header-sticky-sgz-item {
			background-color: #fff;
			width: 180rpx;
			height: 50rpx;
			line-height: 50rpx;
			text-align: center;
			border-radius: 20rpx;
			font-size: 26rpx;
			border: 1rpx solid #f0f0f0;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		}
	}

	.header {
		padding: 20rpx 30rpx;
		background-color: transparent;

		.header-select,
		.header-data {
			background-color: rgba(255, 255, 255, .8);
			backdrop-filter: blur(5px);
			border-radius: 30rpx;
			padding: 10rpx 40rpx;
			margin-bottom: 20rpx;
		}

		.header-select {
			display: flex;
			align-items: center;
			padding-right: 0;

			.image {
				width: 35rpx;
				flex-shrink: 0;
			}

			.single-line {
				flex: 1;
				background-color: transparent !important;
			}

			::v-deep .uni-list-item {
				background-color: transparent !important;
				padding: 0 !important;
			}
		}

		.header-data {
			padding-top: 20rpx;

			.header-data-dzxc {
				display: flex;
				justify-content: space-between;
				align-items: center;
				color: #333;
				font-weight: bold;
				margin-bottom: 10rpx;

				.generate-album-btn {
					width: 180rpx;
				}
			}

			.data-container {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 10rpx;

				.data-item {
					display: flex;
					flex-direction: column;
					align-items: center;

					.data-label {
						font-size: 24rpx;
						color: #666;
					}

					.data-value {
						font-size: 36rpx;
						font-weight: bold;
						color: #333;
					}
				}
			}
		}
	}

	.content-area {
		.timeline-container {
			background-color: transparent;
		}

		.post-list-container {
			background-color: #f8f8f8;
		}
	}

	// 生成电子相册确认弹框
	.SelectAddressPopupStyle {
		z-index: 99999;
		width: 90vw;
		background: linear-gradient(135deg, rgba(240, 240, 240, 0.7), rgba(220, 220, 220, 0.5));
		border-radius: 20rpx;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
		backdrop-filter: blur(8rpx);
		-webkit-backdrop-filter: blur(8rpx);

		.header-title,
		.footer-btn,
		.footer-btn-item {
			touch-action: none;
		}

		.header-title {
			padding: 30rpx 50rpx;
		}

		.footer-btn {
			display: flex;
			padding: 30rpx;
			gap: 30rpx;

			.footer-btn-item {
				flex: 1;
				text-align: center;
				padding: 20rpx 0;
				border-radius: 30rpx;
				font-size: 28rpx;
				font-weight: 500;
			}

			.confirm {
				background: linear-gradient(to right, #FFD700, #FFA500);
				color: #fff;
			}

			.cancel {
				background-color: rgba(255, 255, 255, 0.5);
				color: #666;
				border: 1rpx solid rgba(0, 0, 0, 0.1);
			}
		}
	}

	.rightPopup-line {
		width: calc(100vw - 300rpx);
		height: 100vh;
		background-color: #fff;
		border-top-left-radius: 40rpx;
		border-bottom-left-radius: 40rpx;
		padding: 0 20rpx 0 0;
		position: relative;
		display: flex;
		flex-direction: column;
		overflow-y: auto;

		.status-bar-placeholder {
			height: var(--status-bar-height);
			width: 100%;
			flex-shrink: 0;
			position: fixed;
			z-index: 99;
			background-color: #fff;
		}

		.rightContent {
			position: relative;
			width: 100%;
			flex: 1;
			padding-bottom: 40rpx;
			padding-top: var(--status-bar-height);

			.rightContent-year {
				margin-bottom: 70rpx;
				margin-left: 20rpx;

				.rightContent-year-top {
					display: flex;
					justify-content: flex-end;
					margin-right: -6rpx;

					.rightContent-year-val {
						font-size: 50rpx;
						font-weight: bold;
						margin-right: 20rpx;
					}

					.rightContent-year-picture {
						display: flex;
						align-items: center;

						image {
							width: 50rpx;
							height: 22rpx;
						}
					}
				}

				.rightContent-year-bottom {
					display: grid;
					grid-template-columns: repeat(3, minmax(100rpx, 1fr));
					gap: 20rpx;
					justify-content: flex-end;
					margin-top: 20rpx;
					margin-right: 20rpx;

					.rightContent-year-bottom-month {
						width: 120rpx;
						height: 80rpx;
						background-color: rgba(237, 238, 239, 1);
						border-radius: 20rpx;
						text-align: center;
						line-height: 80rpx;
						font-size: 30rpx;
						color: #333;
					}
				}
			}
		}

		.rightImg {
			position: absolute;
			top: 0;
			right: 20rpx;
			width: 10rpx;
			height: 100%;

			image {
				width: 100%;
				height: 100%;
			}
		}
	}
</style>